package com.cyrus.vueboot.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyrus.vueboot.mapper.auth.AdminMapper;
import com.cyrus.vueboot.mapper.auth.AuthorityMapper;
import com.cyrus.vueboot.mapper.log.LoginLogMapper;
import com.cyrus.vueboot.pojo.auth.Admin;
import com.cyrus.vueboot.pojo.auth.Authority;
import com.cyrus.vueboot.pojo.log.loginLog;
import com.cyrus.vueboot.utils.SplitUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.security.util.Password;

import java.util.*;

/**
 * @Author: Cyrus
 * @CreateDate: 2020/11/14
 */
@Service
@Transactional
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    AuthorityMapper authorityMapper;

    @Autowired
    LoginLogMapper loginLogMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username));
        if (admin == null) {
            return null;
        } else {
            if (admin.getStatus() == 0) {
                return null;
            }
            Authority authority = authorityMapper.selectOne(new QueryWrapper<Authority>().eq("a_authName", admin.getAuthority()));
            //工具类遍历权限
            List<String> auths = SplitUtil.Split(authority);
            //设置权限
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            for (String auth : auths) {
                authorities.add(new SimpleGrantedAuthority(auth));
            }
            //SpringSecurity登陆User信息
            User user = new User(admin.getUsername(), admin.getPassword(), authorities);

            loginLog log = new loginLog();
            log.setLogindate(DateUtil.now());
            log.setLoginuser(admin.getUsername());
            log.setSerialid(UUID.randomUUID().toString());
            loginLogMapper.insert(log);
            return user;
        }
    }

}

